<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>初试MongoDB学习之Mongoose的使用 | Anson&#39;s Blog | 种一棵树最好的时间在十年前，其次是现在。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="NodeJS,MongoDB">
    <meta name="description" content="mongoose简介mongoose官网：https://mongoosejs.com/ 为什么要用Mongoose Mongoose就是一个让我们可以通过Node来操作MongoDB的一个模块。Mongoose本质是一个对象文档模型（ODM）库，他对Node原生的MongoDB模块进行了一部优化封装，并且提供了更多的功能。  Mongoose的优势 可以像操作对象一样操作数据库 可以为文档创建一">
<meta name="keywords" content="NodeJS,MongoDB">
<meta property="og:type" content="article">
<meta property="og:title" content="初试MongoDB学习之Mongoose的使用">
<meta property="og:url" content="http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/index.html">
<meta property="og:site_name" content="Anson&#39;s Blog">
<meta property="og:description" content="mongoose简介mongoose官网：https://mongoosejs.com/ 为什么要用Mongoose Mongoose就是一个让我们可以通过Node来操作MongoDB的一个模块。Mongoose本质是一个对象文档模型（ODM）库，他对Node原生的MongoDB模块进行了一部优化封装，并且提供了更多的功能。  Mongoose的优势 可以像操作对象一样操作数据库 可以为文档创建一">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7072486-22be72d3058566fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7072486-25dcaed274322130.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7072486-cef62c6a437fa126.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-12-21T08:20:27.716Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="初试MongoDB学习之Mongoose的使用">
<meta name="twitter:description" content="mongoose简介mongoose官网：https://mongoosejs.com/ 为什么要用Mongoose Mongoose就是一个让我们可以通过Node来操作MongoDB的一个模块。Mongoose本质是一个对象文档模型（ODM）库，他对Node原生的MongoDB模块进行了一部优化封装，并且提供了更多的功能。  Mongoose的优势 可以像操作对象一样操作数据库 可以为文档创建一">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/7072486-22be72d3058566fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    
        <link rel="alternate" type="application/atom+xml" title="Anson&#39;s Blog" href="/atom.xml">
    
    <link rel="shortcut icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu"  >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="https://yscoder.github.io/img/face.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">张宁乐</h5>
          <a href="mailto:zhangningle2017@gmail.com" title="zhangningle2017@gmail.com" class="mail">zhangningle2017@gmail.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about"  >
                <i class="icon icon-lg icon-user"></i>
                关于
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/ansonznl" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">初试MongoDB学习之Mongoose的使用</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">初试MongoDB学习之Mongoose的使用</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-11-23T09:28:55.000Z" itemprop="datePublished" class="page-time">
  2018-11-23
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mongoose简介"><span class="post-toc-number">1.</span> <span class="post-toc-text">mongoose简介</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#为什么要用Mongoose"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">为什么要用Mongoose</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Mongoose的优势"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">Mongoose的优势</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用Mongoose"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">使用Mongoose</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mongoose基本使用"><span class="post-toc-number">2.</span> <span class="post-toc-text">mongoose基本使用</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#mongoose的几个新的对象"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">mongoose的几个新的对象</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#定义一个Schema（表-模式对象）"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">定义一个Schema（表/ 模式对象）</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#创建model（集合）"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">创建model（集合）</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mongoose-插入和查询"><span class="post-toc-number">3.</span> <span class="post-toc-text">mongoose 插入和查询</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#插入多条数据"><span class="post-toc-number">3.1.</span> <span class="post-toc-text">插入多条数据</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#查询"><span class="post-toc-number">3.2.</span> <span class="post-toc-text">查询</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#查询所有"><span class="post-toc-number">3.3.</span> <span class="post-toc-text">查询所有</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#mongoose-修改和删除"><span class="post-toc-number">4.</span> <span class="post-toc-text">mongoose 修改和删除</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#修改方法："><span class="post-toc-number">4.1.</span> <span class="post-toc-text">修改方法：</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#删除方法"><span class="post-toc-number">4.2.</span> <span class="post-toc-text">删除方法</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#统计文档条数"><span class="post-toc-number">4.3.</span> <span class="post-toc-text">统计文档条数</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Entity"><span class="post-toc-number">5.</span> <span class="post-toc-text">Entity</span></a></li></ol>
        </nav>
    </aside>


<article id="post-MongoDB学习之Mongoose的使用"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">初试MongoDB学习之Mongoose的使用</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-11-23 17:28:55" datetime="2018-11-23T09:28:55.000Z"  itemprop="datePublished">
2018-11-23
<!--2018-12-21 16:20:27-->
</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h3 id="mongoose简介"><a href="#mongoose简介" class="headerlink" title="mongoose简介"></a>mongoose简介</h3><p>mongoose官网：<a href="https://mongoosejs.com/" target="_blank" rel="noopener">https://mongoosejs.com/</a></p>
<h4 id="为什么要用Mongoose"><a href="#为什么要用Mongoose" class="headerlink" title="为什么要用Mongoose"></a>为什么要用Mongoose</h4><blockquote>
<p>Mongoose就是一个让我们可以通过Node来操作MongoDB的一个模块。<br>Mongoose本质是一个对象文档模型（ODM）库，<br>他对Node原生的MongoDB模块进行了一部优化封装，并且提供了更多的功能。</p>
</blockquote>
<h4 id="Mongoose的优势"><a href="#Mongoose的优势" class="headerlink" title="Mongoose的优势"></a>Mongoose的优势</h4><ol>
<li>可以像操作对象一样操作数据库</li>
<li>可以为文档创建一个模式结构（Schema）</li>
<li>可以对模型中的文档/文档进行验证</li>
<li>数据可以通过类型转换为对象模型</li>
<li>可以使用中间件来应用业务逻辑挂钩</li>
<li>比Node原生的MongoDB驱动更容易</li>
</ol>
<h4 id="使用Mongoose"><a href="#使用Mongoose" class="headerlink" title="使用Mongoose"></a>使用Mongoose</h4><ol>
<li><p>下载安装mongoose模块<br><code>cnpm install mongoose --save</code></p>
</li>
<li><p>引用mongoose：<br><code>var mongoose =require(&quot;mongoose&quot;);</code></p>
</li>
<li>使用”mongoose”连接数据库：<br><code>var db =mongoose.connect(&quot;mongodb://user:pass@localhost:port/database&quot;);</code></li>
<li>执行下面代码检查默认数据库test，是否可以正常连接成功?<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var mongoose =require(&quot;mongoose&quot;);</span><br><span class="line">var db =mongoose.connect(&quot;mongodb://localhost/m_data&quot;);</span><br><span class="line">db.connection.on(&quot;error&quot;,function (error) &#123;</span><br><span class="line">   console.log(&quot;数据库连接失败：&quot; + error);</span><br><span class="line">&#125;);</span><br><span class="line">db.connection.on(&quot;open&quot;,function () &#123;</span><br><span class="line">   console.log(&quot;数据库连接成功！&quot;);</span><br><span class="line">&#125;);</span><br><span class="line">db.connection.once(&apos;close&apos;, ()=&gt;&#123;</span><br><span class="line">    console.log(&apos;连接已经断开成功！&apos;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="mongoose基本使用"><a href="#mongoose基本使用" class="headerlink" title="mongoose基本使用"></a>mongoose基本使用</h3><h4 id="mongoose的几个新的对象"><a href="#mongoose的几个新的对象" class="headerlink" title="mongoose的几个新的对象"></a>mongoose的几个新的对象</h4><p>在MongoDB中，多个Document可以组成Collection(以下简称集合)，多个集合又可以组成数据库。我们想要操作MongoDB数据，那就得先要具备上面所说的包含数据的“文档”，文档又是什么意思呢，请看如下介绍。</p>
<ol>
<li><strong>文档</strong> —— 是MongoDB的核心概念，是键值对的一个有序集，在JavaScript里文档被表示成对象。同时它也是MongoDB中数据的基本单元，非常类似于关系型数据库管理系统中的行，但更具表现力。</li>
<li><strong>集合</strong> —— 由一组文档组成，如果将MongoDB中的一个文档比喻成关系型数据库中的一行，那么一个集合就相当于一张表。</li>
<li><strong>Schema</strong>—— 一种以文件形式存储的数据库模型骨架，无法直接通往数据库端，也就是说它不具备对数据库的操作能力，仅仅只是<strong>定义数据的类型</strong>，可以说是数据属性模型(传统意义的表结构)，又或着是“集合”的模型骨架。<br><strong>mongoose中任何任何事物都是从Schema开始的</strong>。每一个Schema对应MongoDB中的一个集合(collection)。Schema中定义了集合中文档(document)的样式。<h4 id="定义一个Schema（表-模式对象）"><a href="#定义一个Schema（表-模式对象）" class="headerlink" title="定义一个Schema（表/ 模式对象）"></a>定义一个Schema（表/ 模式对象）</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">//新建Schema 定义规则/字段的规则</span><br><span class="line">let Schema= mongoose.Schema;</span><br><span class="line">//定义personSchema的字段（规则）需要new一下 有点像构造函数的样子</span><br><span class="line">let personSchema= new Schema(&#123;</span><br><span class="line">    name: String,</span><br><span class="line">    sex: String,</span><br><span class="line">    age: Number</span><br><span class="line">&#125;);</span><br><span class="line">`</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><strong>基本属性类型有</strong>： </p>
<ul>
<li>String</li>
<li>Number</li>
<li>Date</li>
<li>Boolean</li>
<li>Buffer</li>
<li>ObjectId</li>
<li>Mixed</li>
<li>Array</li>
</ul>
<p><strong>Model</strong>—— 由Schema构造生成的模型，根据Schema定义的数据类型规则，可操作具体的符合改规则的数据。</p>
<h4 id="创建model（集合）"><a href="#创建model（集合）" class="headerlink" title="创建model（集合）"></a>创建model（集合）</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">let personModel= mongoose.model(&apos;person&apos;, personSchema);</span><br></pre></td></tr></table></figure>
<p>  person：数据库中的集合名称,当我们对其添加数据时如果person已经存在，则会保存到其目录下，如果未存在，则会创建person集合，然后在保存数据。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">//4. 插入文档</span><br><span class="line">personModel.create(&#123;</span><br><span class="line">    name: &apos;张宁乐&apos;,</span><br><span class="line">    sex: &apos;男&apos;,</span><br><span class="line">    age: 18</span><br><span class="line">&#125;, (err)=&gt;&#123;</span><br><span class="line">   if(!err)&#123;</span><br><span class="line">       console.log(&apos;插入成功！&apos;)</span><br><span class="line">   &#125;else&#123;</span><br><span class="line">       throw err;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<h3 id="mongoose-插入和查询"><a href="#mongoose-插入和查询" class="headerlink" title="mongoose 插入和查询"></a>mongoose 插入和查询</h3><p>mongoose查找数据的一些方法：<br><a href="https://mongoosejs.com/docs/api.html#model_Model.find" target="_blank" rel="noopener">https://mongoosejs.com/docs/api.html#model_Model.find</a></p>
<h4 id="插入多条数据"><a href="#插入多条数据" class="headerlink" title="插入多条数据"></a>插入多条数据</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">personModel.create([</span><br><span class="line">    &#123;name:&apos;张逗逗&apos;,age: 2,sex: &apos;男&apos;&#125;,</span><br><span class="line">    &#123;name:&apos;牛嘻嘻&apos;,age: 2,sex: &apos;女&apos;&#125;</span><br><span class="line">], (err)=&gt;&#123;</span><br><span class="line">   if(!err)&#123;</span><br><span class="line">       console.log(&apos;插入成功！&apos;)</span><br><span class="line">   &#125;else&#123;</span><br><span class="line">       throw err;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h4><ul>
<li>Model.find() <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">personModel.find(&#123;name: &apos;张宁乐&apos;&#125;, (err, data)=&gt;&#123;</span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(data)</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        throw err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="查询所有"><a href="#查询所有" class="headerlink" title="查询所有"></a>查询所有</h4><ul>
<li>Model.find({}, callback) <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">personModel.find(&#123;&#125;, (err, data)=&gt;&#123;</span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(data)</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        throw err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>也可以选择查找数据的条件（0隐藏 1显示 id默认显示） 和MongoDB在命令行中的使用方法一样<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">//查询时只显示name </span><br><span class="line">personModel.find(&#123;&#125;, &#123;name: 1, _id: 0&#125;, (err,data)=&gt;&#123;</span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(data)</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        throw err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>在<code>find()</code>中  <code>skip</code>（查询开始的位置）和<code>limit</code>（增加的条数）也可以使用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">personModel.find(&#123;&#125;, &#123;name: 1, _id: 0, age: 1&#125;, &#123;skip: 0, limit: 2&#125;, (err, data)=&gt;&#123;</span><br><span class="line">    //只显示name 和 age   从第1开始 每次查询2条 </span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(data)</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        throw err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p><strong>MongoDB的find()、findOne() 等命令在 mongoose里都可以使用</strong><br>具体可参考 ：<a href="https://mongoosejs.com/docs/api.html#model_Model.find" target="_blank" rel="noopener">https://mongoosejs.com/docs/api.html#model_Model.find</a></p>
<h3 id="mongoose-修改和删除"><a href="#mongoose-修改和删除" class="headerlink" title="mongoose 修改和删除"></a>mongoose 修改和删除</h3><p>参考： <a href="https://mongoosejs.com/docs/api.html#model_Model.update" target="_blank" rel="noopener">https://mongoosejs.com/docs/api.html#model_Model.update</a></p>
<h4 id="修改方法："><a href="#修改方法：" class="headerlink" title="修改方法："></a>修改方法：</h4><ul>
<li>Model.update()</li>
<li>Model.updateMany()</li>
<li>Model.updateOne()</li>
<li>Model.watch()</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">personModel.update(&#123;name: &apos;张宁乐&apos;&#125;, &#123;$set: &#123;age: 20&#125;&#125;, (err, data)=&gt;&#123;</span><br><span class="line">   if(!err)&#123;</span><br><span class="line">       console.log(&apos;修改成功！&apos;)</span><br><span class="line">       console.log(data)</span><br><span class="line">   &#125;else&#123;</span><br><span class="line">       throw err;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://upload-images.jianshu.io/upload_images/7072486-22be72d3058566fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="4a9f49d480f66c5a64cb9a833459fdd.png" title="">
                </div>
                <div class="image-caption">4a9f49d480f66c5a64cb9a833459fdd.png</div>
            </figure>
<h4 id="删除方法"><a href="#删除方法" class="headerlink" title="删除方法"></a>删除方法</h4><ul>
<li>Model.remove()</li>
<li>Model.deleteMany()</li>
<li>Model.deleteOne()<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">personModel.remove(&#123;name:&apos;牛嘻嘻&apos;&#125;, (err)=&gt;&#123;</span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(&apos;删除成功！&apos;)</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        throw err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="统计文档条数"><a href="#统计文档条数" class="headerlink" title="统计文档条数"></a>统计文档条数</h4><ul>
<li>Model.count() <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">personModel.count(&#123;&#125;, (err,count)=&gt;&#123;</span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(&apos;查询条数成功！ 一共：&apos; + count + &apos;条&apos;);</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        throw err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://upload-images.jianshu.io/upload_images/7072486-25dcaed274322130.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2b7684dc310af51ac7fb50e5daa1123.png" title="">
                </div>
                <div class="image-caption">2b7684dc310af51ac7fb50e5daa1123.png</div>
            </figure>
<h3 id="Entity"><a href="#Entity" class="headerlink" title="Entity"></a>Entity</h3><p> Entity—— 由Model创建的实体，使用save方法保存数据，Model和Entity的操作都能影响数据库的操作，但Model比Entity更具操作性。<br>使用Model创建Entity，如下示例:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">let mongoose= require(&apos;mongoose&apos;);</span><br><span class="line">let db= mongoose.connection(&apos;mongodb://localhost/m_data&apos;);</span><br><span class="line">db.on(&apos;open&apos;, ()=&gt;&#123;</span><br><span class="line">    console.log(&apos;连接成功！&apos;)</span><br><span class="line">&#125;)</span><br><span class="line">let Schema= mongoose.Schema;</span><br><span class="line">let personSchema= new Schema(&#123;</span><br><span class="line">    name: String,</span><br><span class="line">    sex: String,</span><br><span class="line">    age: Number</span><br><span class="line">&#125;);</span><br><span class="line">let personModel= mongoose.model(&apos;person&apos;, personSchema);</span><br><span class="line">let personEntity = new personModel(&#123;</span><br><span class="line">    name: &apos;许巍&apos;,</span><br><span class="line">    sex: &apos;男&apos;,</span><br><span class="line">    age: 38</span><br><span class="line">&#125;)</span><br><span class="line">personEntity.save((err, person)=&gt;&#123;</span><br><span class="line">    if(!err)&#123;</span><br><span class="line">        console.log(&apos;保存成功！&apos;)</span><br><span class="line">        console.log(person);</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        console.log(&apos;保存失败！&apos;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://upload-images.jianshu.io/upload_images/7072486-cef62c6a437fa126.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="c85c9b12f87f890e10e74f23555c802.png" title="">
                </div>
                <div class="image-caption">c85c9b12f87f890e10e74f23555c802.png</div>
            </figure>
<p>参考：<a href="https://blog.csdn.net/swimming_in_IT_/article/details/80723866" target="_blank" rel="noopener">https://blog.csdn.net/swimming_in_IT_/article/details/80723866</a></p>

        </div>

        <blockquote class="post-copyright">
    
    <footer>
        <a href="http://yoursite.com">
            <img src="https://yscoder.github.io/img/face.jpg" alt="张宁乐">
            张宁乐
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/MongoDB/">MongoDB</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/NodeJS/">NodeJS</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/&title=《初试MongoDB学习之Mongoose的使用》 — Anson's Blog&pic=https://yscoder.github.io/img/face.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/&title=《初试MongoDB学习之Mongoose的使用》 — Anson's Blog&source=张宁乐,博客" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《初试MongoDB学习之Mongoose的使用》 — Anson's Blog&url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2018/12/11/JavaScript的预编译过程分析/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">JavaScript的预编译过程分析</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2018/11/17/MongoDB中常用语句/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">MongoDB中常用语句</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "gbSwUaucLkuxqOLxm131Mg9U-gzGzoHsz",
            appKey: "b9xU2qIPrm06S0uymbAfrGMD",
            avatar: "mm",
            placeholder: "要不要说点什么？",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>张宁乐 &copy; 2017 - 2019</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
			<span>
					Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>
			  </span>
        </p>
    </div>
</footer>
<!-- <script>
(function(){
    var bp = document.createElement("script");
    var curProtocol = window.location.protocol.split(":")[0];
    if (curProtocol === "https") {
        bp.src = "https://zz.bdstatic.com/linksubmit/push.js";
    }
    else {
        bp.src = "http://push.zhanzhang.baidu.com/push.js";
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script> -->

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/&title=《初试MongoDB学习之Mongoose的使用》 — Anson's Blog&pic=https://yscoder.github.io/img/face.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/&title=《初试MongoDB学习之Mongoose的使用》 — Anson's Blog&source=张宁乐,博客" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《初试MongoDB学习之Mongoose的使用》 — Anson's Blog&url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/11/23/MongoDB学习之Mongoose的使用/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
